package data;

import java.util.ArrayList;

import models.AutoSite;
import models.User;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class UserData {
	private Objectify ofy;
	
	private int limit = 20;	
	
	private int page = 1;
	
	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public UserData() {
		try {
			ObjectifyService.register(User.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public void insert(User user) {
		ofy.put(user);
	}
	
	public User getById(String userId) {
		User user  = new User();
		try {
			user = ofy.get(new Key<User>(User.class, userId));
		} catch (Exception e) {
			user = null;
		}
		return user;
	}
	
	public ArrayList<User> list() {
		ArrayList<User> users = new ArrayList<User>();
		
		int start = (page - 1) * limit;
		Query<User> q = ofy.query(User.class).limit(limit).offset(start);
		for (User user: q) {
			users.add(user);
		}
		
		return users;
	}
	public void delete(User user) {
		ofy.delete(user);
	}
	
	public void deleteById(String userId) {
		User user = (User) getById(userId);
		if (user != null) {
			delete(user);
		}
	}
}
